package com.doudou.oauth.service;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.springframework.cache.Cache;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;


/**
 * @Author: 傻男人
 * @Date: 2020/6/10 9:41
 * @Version: 1.0
 * @Description: 授权码服务
 */
public class CacheAuthorizationCodeServices implements AuthorizationCodeServices {

    RedisTemplate redisTemplate;

    Cache authCache;

    public CacheAuthorizationCodeServices(RedisTemplate redisTemplate) {
//        if(cacheManager == null){
//            throw  new IllegalArgumentException("cacheManager 不能为null");
//        }
        this.redisTemplate = redisTemplate;
    }


//    @PostConstruct
//    public void init(){
//        authCache = this.cacheManager.getCache("auth_code");
//    }

    @Override
    public String createAuthorizationCode(OAuth2Authentication authentication) {
        String key = IdWorker.get32UUID();
        redisTemplate.opsForValue().set(key,authentication);
        return key;
    }

    @Override
    public OAuth2Authentication consumeAuthorizationCode(String code) throws InvalidGrantException {
        OAuth2Authentication authentication =  (OAuth2Authentication)redisTemplate.opsForValue().get(code);
        if (authentication == null) {
            throw new InvalidGrantException("授权码失效: " + code);
        }
        redisTemplate.delete(code);
        return authentication;
    }



}

